package com.zkingsoft.zkingbase.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.SystemClock;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zkingsoft.zkingbase.R;

import java.util.Locale;

/**
 * Created by ytf on 2016/11/8.
 * 输入框的封装
 */
public class NormalInputBox extends RelativeLayout implements ViewTreeObserver.OnGlobalLayoutListener
{
    private static final String TEXT = "text";
    private static final String PASSWORD = "password";
    private static final String NUMBER = "number";

    private String inputType = TEXT;
    private String hintText = "";
    private int charLength = -1;
    private Drawable icon = null;
    private int defaultColor = Color.parseColor("#FFFFFFFF");
    private int textColor;
    private int waitTextColor;
    private int textSize = 15;
    private int cutTextSize;
    private boolean showVariWait;
    private String sendText;
    private String retryText;
    private boolean hasFocus;
    private Paint mHightlightStrokePaint;
    private RectF mRectF;

    public NormalInputBox(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.NormalInputBox);
        inputType = typedArray.getString(R.styleable.NormalInputBox_inputType);
        sendText = typedArray.getString(R.styleable.NormalInputBox_sendText);
        if (sendText == null)
        {
            sendText = "发送验证码";
        }
        retryText = typedArray.getString(R.styleable.NormalInputBox_retryText);
        if (retryText == null)
        {
            retryText = "重新发送";
        }
        hintText = typedArray.getString(R.styleable.NormalInputBox_hintText);
        charLength = typedArray.getInt(R.styleable.NormalInputBox_charLength, -1);
        icon = typedArray.getDrawable(R.styleable.NormalInputBox_iconMark);
        textColor = typedArray.getColor(R.styleable.NormalInputBox_textColor, defaultColor);
        waitTextColor = typedArray.getColor(R.styleable.NormalInputBox_waitTextColor, defaultColor);
        textSize = typedArray.getInteger(R.styleable.NormalInputBox_textSize, 15);
        cutTextSize = textSize -3;
        showVariWait = typedArray.getBoolean(R.styleable.NormalInputBox_showVariWait, false);
        typedArray.recycle();
        init();
    }

    private ImageView deleteIcon, iv;
    private EditText etContent;
    private RelativeLayout rt;
    private TextView tvVariWait;
    private View divider;

    private void init()
    {
        View v = LayoutInflater.from(getContext()).inflate(R.layout.normal_input_box, null, false);

        addView(v);

        etContent = (EditText) v.findViewById(R.id.et_content);
        deleteIcon = (ImageView) v.findViewById(R.id.delete);
        iv = (ImageView) v.findViewById(R.id.iv);
        rt = (RelativeLayout) v.findViewById(R.id.rt);
        tvVariWait = (TextView) v.findViewById(R.id.tv_varicode_wait);
        divider = v.findViewById(R.id.divider);
        if (showVariWait)
        {
            divider.setVisibility(View.VISIBLE);
            deleteIcon.setVisibility(View.GONE);
            tvVariWait.setVisibility(View.VISIBLE);
            tvVariWait.setText(sendText);
        } else
        {
            tvVariWait.setVisibility(View.GONE);
        }
        //图标设置
        if (icon != null)
        {
            iv.setBackgroundDrawable(icon);
        }
        //提示设置
        if (!TextUtils.isEmpty(hintText))
        {
            etContent.setHint(hintText);
        }
        //长度限制
        if (charLength != -1)
        {
            etContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(charLength)});
        }
        //输入类型设置
        if (inputType.equals(PASSWORD))
        {
            etContent.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        } else if (inputType.equals(NUMBER))
        {
            etContent.setInputType(InputType.TYPE_CLASS_NUMBER);
        } else
        {
            etContent.setInputType(InputType.TYPE_CLASS_TEXT);
        }

        etContent.setTextColor(textColor);

        etContent.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize);
        tvVariWait.setTextSize(TypedValue.COMPLEX_UNIT_SP, cutTextSize);
        tvVariWait.setTextColor(waitTextColor);

        deleteIcon.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                etContent.setText("");
            }
        });
        etContent.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2)
            {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2)
            {
                String str = charSequence.toString();
                if (!TextUtils.isEmpty(str))
                {
                    if (!showVariWait)
                    {
                        deleteIcon.setVisibility(View.VISIBLE);
                    }
                } else
                {
                    deleteIcon.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable)
            {
            }
        });
        if(showStroke)
        {
            etContent.setOnFocusChangeListener(new OnFocusChangeListener()
            {
                @Override
                public void onFocusChange(View v, boolean hasFocus)
                {
                    if(hasFocus)
                    {
                        NormalInputBox.this.hasFocus = true;
                        requestLayout();
                    }else
                    {
                        NormalInputBox.this.hasFocus = false;
                        requestLayout();
                    }
                }
            });
        }
        tvVariWait.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if(listener != null)
                {
                    if(listener.onSendVarificationCode())
                    {
                        sendVarificationCode(60, retryText);
                    }
                }
            }
        });

        mHightlightStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mHightlightStrokePaint.setColor(textColor);
        mHightlightStrokePaint.setStyle(Paint.Style.STROKE);
        mHightlightStrokePaint.setStrokeWidth(2);
    }

    private boolean showStroke;
    public void showStroke()
    {
        showStroke = true;
    }

    @Override
    protected void dispatchDraw(Canvas canvas)
    {
        super.dispatchDraw(canvas);
        if(hasFocus)
        {
            canvas.drawRoundRect(mRectF, height/10, height/10, mHightlightStrokePaint);
        }
    }

    public void setSendText(String str)
    {
        sendText = str;
    }

    public void setRetryText(String str)
    {
        retryText = str;
    }

    private OnVarificationClickListener listener;

    public void setOnVarificationClickListener(OnVarificationClickListener listener)
    {
        this.listener = listener;
    }
    public interface OnVarificationClickListener
    {
        /***
         * 返回true表示已经点击了发送验证码
         * @return
         */
        boolean onSendVarificationCode();
    }

    public void setText(String str)
    {
        etContent.setText(str);
    }

    private boolean sendOrRetry = true;

    /***
     * 发送验证码
     *
     * @param hintText 提示文字，比如“重新发送”
     */
    private void sendVarificationCode(int seconds, String hintText)
    {
        if (showVariWait)
        {
            task = new CutDownThread(seconds, hintText);
            task.start();
        }
    }

    public void cancelTimeCutDown()
    {
        onGoing = false;
        sendOrRetry = true;
        tvVariWait.setTextColor(waitTextColor);
        tvVariWait.setClickable(true);
        tvVariWait.setText(sendText);
    }

    private CutDownThread task;
    private boolean onGoing;

    class CutDownThread extends Thread
    {

        private int seconds;
        private String hintText;

        public CutDownThread(int seconds, String hintText)
        {
            this.seconds = seconds;
            this.hintText = hintText;

//            tvVariWait.setTextSize(TypedValue.COMPLEX_UNIT_SP, cutTextSize);
//            TextPaint tp = tvVariWait.getPaint();
//            int wid = (int) StaticLayout.getDesiredWidth(sendText, tp);
//            wid = AutoUtils.getPercentWidthSizeBigger(wid);
//            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(wid, ViewGroup.LayoutParams.WRAP_CONTENT);
//            params.leftMargin = (int) UIHelper.px2dp(getContext(), 20);
//            tvVariWait.setLayoutParams(params);
        }

        @Override
        public void run()
        {
            onGoing = true;

            while (onGoing && (seconds > 0))
            {
                seconds--;
                SystemClock.sleep(1000);
                NormalInputBox.this.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        tvVariWait.setText(hintText + String.format(Locale.CHINA, "%02d", seconds) + "S");
                    }
                });
            }
            if (seconds == 0)
            {
                sendOrRetry = false;
                onGoing = false;
                NormalInputBox.this.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        tvVariWait.setTextSize(TypedValue.COMPLEX_UNIT_SP, cutTextSize);
                        tvVariWait.setText(retryText);
                        tvVariWait.setTextColor(waitTextColor);
                        tvVariWait.setClickable(true);
                    }
                });

            }
        }
    }

    @Override
    protected void onAttachedToWindow()
    {
        super.onAttachedToWindow();
        getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    @Override
    protected void onDetachedFromWindow()
    {
        cancelTimeCutDown();
        getViewTreeObserver().removeGlobalOnLayoutListener(this);
        super.onDetachedFromWindow();
    }

    public String getContent()
    {
        CharSequence cs = etContent.getText();
        return TextUtils.isEmpty(cs) ? "" : etContent.getText().toString();
    }

    private boolean isLayouted;

    private int width;
    private int height;

    @Override
    public void onGlobalLayout()
    {
        if(!isLayouted)
        {
            isLayouted = true;
            width = getWidth();
            height = getHeight();
            mRectF = new RectF(0, getPaddingTop(), width, height);
//            int temp = Math.min(width, height);
//            int padding = 50;
//            int tetSize = temp - padding;
//            rt.setPadding(padding, padding, padding, padding);
//            rt.requestLayout();
        }
    }
}
